<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>客户列表</title>
	<meta name="renderer" content="webkit">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
	<meta name="apple-mobile-web-app-status-bar-style" content="black">
	<meta name="apple-mobile-web-app-capable" content="yes">
	<meta name="format-detection" content="telephone=no">
	<link rel="stylesheet" href="plugins/layui/css/layui.css" media="all" />
	<link rel="stylesheet" href="//at.alicdn.com/t/font_tnyc012u2rlwstt9.css" media="all" />
</head>
<body class="childrenBody">
	<blockquote class="layui-elem-quote news_search">
		<form class="layui-form">

			<div class="layui-inline dynamicShow1">
				<label class="layui-form-label">门店</label>
				<div class="layui-input-block">
					<select name="merchantId" id="merchantId">
						<option value="">--请选择门店--</option>
					</select>
				</div>
			</div>


			<div class="layui-inline">
				<label class="layui-form-label">客户类型</label>
				<div class="layui-input-block">
					<select name="type" id="type">
						<option value="">--请选择类型--</option>
						<option value="1">普通客户</option>
						<option value="2">VIP客户</option>
					</select>
				</div>
			</div>
        <div class="layui-inline">
            <label class="layui-form-label">姓名</label>
            <div class="layui-input-block">
                <input type="text" class="layui-input" name="name" placeholder="请输入姓名">
            </div>
        </div>
        
        <div class="layui-inline">
            <label class="layui-form-label">手机号码</label>
            <div class="layui-input-block">
                <input type="text" class="layui-input" name="phone" placeholder="请输入手机号码">
            </div>
        </div>
			<div class="layui-inline">
				<label class="layui-form-label">车牌号码</label>
				<div class="layui-input-block">
					<input type="text" class="layui-input" name="plateNumber" placeholder="请输入车牌号码">
				</div>
			</div>


			<div class="layui-inline">
				<label class="layui-form-label">消费范围</label>
				<div class="layui-input-inline" style="width: 100px;">
					<input type="text" name="minConsumeMoney" placeholder="￥" autocomplete="off" class="layui-input">
				</div>
				<div class="layui-form-mid">-</div>
				<div class="layui-input-inline" style="width: 100px;">
					<input type="text" name="maxConsumeMoney" placeholder="￥" autocomplete="off" class="layui-input">
				</div>
			</div>

        <div class="layui-inline">
            <a class="layui-btn search_btn" lay-submit="" lay-filter="queryCustomer">查询</a>
        </div>

        <div class="layui-inline dynamicShow " >
           <a class="layui-btn layui-btn-normal membersAdd_btn">添加客户</a>
        </div>
          <div class="layui-inline dynamicShow">
          	<button type="button" class="layui-btn" id="test1">
  			<i class="layui-icon">&#xe67c;</i>批量上传
			</button>
        </div>
         <div class="layui-inline dynamicShow">
          	 <a class="layui-btn layui-btn-normal" href="/customer/template/down">下载模板文件</a>
        </div>

    </form>
		
	</blockquote>
	<div class="layui-form news_list">
	  	<table class="layui-table" id="memberList" lay-filter="members"></table>
	</div>
	<div id="page"></div>
	<script type="text/javascript" src="js/jquery-1.11.2.min.js"></script>
	<script type="text/javascript" src="plugins/layui/layui.all.js"></script>
	<script type="text/javascript" src="js/user/newsList.js"></script>
	
	<script type="text/html" id="barDemo">
		<a class="layui-btn layui-btn-xs" lay-event="edit"><i class="iconfont icon-edit"></i>编辑</a>
 		<a class="layui-btn layui-btn-xs" lay-event="sendGift"><i class="layui-icon">&#xe609;</i>发礼包</a>
	    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del"><i class="layui-icon"></i>删除</a>
	  </script>
	<script type="text/javascript">
	//重新渲染表单
	function renderForm(){
	  layui.use('form', function(){
	   var form = layui.form;
	   form.render();
	  });
	 }
	
	layui.config({
		base : '/js/admin/'
	}).extend({
		ajaxExtention : 'ajaxExtention',//加载自定义扩展，每个业务js都需要加载这个ajax扩展
		$tool : 'tool'
	}).use(['table','form','upload','$tool'], function(){
	    var table = layui.table;
	    var form = layui.form;//高版本建议把括号去掉，有的低版本，需要加()
	    var upload = layui.upload;
	    var $tool = layui.$tool;
        $.ajax({
            type : "GET",
            url: '/merchants/merchants.json',
            dataType:'json',
            async:false,
            success: function(data){
                var list=data.data;
                var html='';
                for(var i=0;i<list.length;i++){
                    html += "<option value='"+list[i].id+"'>"+list[i].name+"</option>"
                }
                $("#merchantId").append(html);
                form.render();
            }
        });

        var isAdminstr=localStorage.getItem("isAdmin");
        var isAdmin=isAdminstr=='true'?true:false;
        if(isAdmin){
            $(".dynamicShow").hide();
            $(".dynamicShow1").show();
        }else {
            $(".dynamicShow").show();
            $(".dynamicShow1").hide();
        }
	    var tableIns=table.render({
	        elem: '#memberList'
	        ,url: '/customer'
	        ,cols: [[
	            {checkbox: true, fixed: true}
	            ,{field:'id', title: 'ID',  sort: true, fixed: true}
	            ,{field:'merchantName', title: isAdmin?'所属门店':'',type:isAdmin?'':'space',style:isAdmin?'':'display:none'}
                ,{field:'type', title: '客户类型',templet:function(d){
                        if(d.type==1){
                            return '普通客户'
                        }else if(d.type==2){
                            return 'VIP客户'
                        }
                    }
				}
	             ,{field:'name', title: '客户姓名'}
	            ,{field:'phone', title: '手机号码'}
	            ,{field:'plateNumbers', title: '车牌号码'}
	            ,{field:'carDescs', title: '车辆信息'}
	             ,{field:'consumeMoney', title: '消费金额'}
	            ,{field:'createTime', title: '创建时间',
	            	templet:function(d){
					 if(d.createTime!=null){
							return $tool.formatTime(d.createTime);
						}else{
							return "---"
						} 
					}}
	            ,{fixed: 'right',title: '操作', align:'center', toolbar: '#barDemo'} //这里的toolbar值是模板元素的选择器
	        ]]
	        ,id: 'testReload'
	        ,page: true
	        ,height: 600
	    });
	    
	    
	    //方法级渲染
	    var uploadInst = upload.render({
		    elem: '#test1' //绑定元素
		    ,url: '/customer/upload' //上传接口
		    ,accept:'file'
		    ,exts:'xls|xlsx'
		    ,done: function(res){
		      //上传完毕回调
                layer.msg(res.msg);
				if(res.code==200){
                    tableIns.reload();
				}


		    }
		    ,error: function(){
		      //请求异常回调
		       layer.msg('上传失败')
		    }
  		});
	    
	    
	    form.on("submit(queryCustomer)", function (data) {
	        var name = data.field.name;
	        var phone = data.field.phone;
	        var type= data.field.type;
            var plateNumber = data.field.plateNumber;
	        var merchantId=data.field.merchantId;
	        var minConsumeMoney=data.field.minConsumeMoney;
            var maxConsumeMoney=data.field.maxConsumeMoney;
            if((minConsumeMoney!='' &&maxConsumeMoney=='') || (minConsumeMoney=='' &&maxConsumeMoney!='')  ){
                layer.msg('请填写正确的消费金额范围');
                return;
			}else{
                var reg = new RegExp("^[0-9]*$");
              	var flag= reg.test(minConsumeMoney);
                var flag2= reg.test(maxConsumeMoney);
                if(!(flag && flag2)){
                    layer.msg('请填写正确的消费金额范围');
                    return;
				}
			}
	        //表格重新加载
	        tableIns.reload({
	            where:{
	                type:type,
                    name:name,
                    phone:phone,
                    plateNumber:plateNumber,
					merchantId:merchantId,
                    minConsumeMoney:minConsumeMoney,
                    maxConsumeMoney:maxConsumeMoney
	            }
	        });

	        return false;
	    });
	    
	    table.on('tool(members)', function(obj){ //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
	    	  var data = obj.data; //获得当前行数据
	    	  var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
	    	  var tr = obj.tr; //获得当前行 tr 的DOM对象
	    	 
	    	  if(layEvent === 'detail'){ //查看
	    	    //do somehing
	    	  } else if(layEvent === 'del'){ //删除
	    	    layer.confirm('真的删除该会员吗', function(index){

	    	      layer.close(index);
	    	      //向服务端发送删除指令
	    	      var ids=obj.data.id;
	    	    //  var merchantId=obj.data.belongMerchantId;
	    	      $.ajax({  
	    	            type: "DELETE",
	    	            url:"/customer/"+ids,
	    	            data:{
	    	                id:ids
						//	merchantId:merchantId
						},// 序列化表单值
	    	            success: function(data1) {  
	    	            	if(data1.code==200){
	    	            		top.layer.close(index);
	    	          			top.layer.msg("删除成功");
                                obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
	    	            	}else{
                                top.layer.msg("删除失败");
							}
	    	            
	    	            } ,
	    	 		
	    		 		 error: function(request) {  
	    		             alert("Connection error");  
	    		         } 
	    	        }); 
	    	    });
	    	  } else if(layEvent === 'edit'){ //编辑
	    	    //do something
	    	     var ids=obj.data.id;
                  var merchantId=obj.data.merchantId;
	    	     editMember(ids,merchantId);
	    	  }else if(layEvent === 'sendGift'){
	    		  var ids=obj.data.id;
                  var merchantId=obj.data.merchantId;
	    		  sendGift(ids,merchantId);
		    	    
	    	  }
	    	});
	});
	

		$(".membersAdd_btn").click(function(){
			var index = layui.layer.open({
				title : "添加会员",
				type : 2,
				area:["1200px","600px"],
				content : "member/membersAdd.html",
				success : function(layero, index){
					
				}
			})			

		});

	
 	 var categoryList;
	  $.ajax({
         type : "GET",
         url: 'categorys/getAlls',
         dataType:'json',
      	  async:false,
         success: function(data){
         	var list=data.data;
         	categoryList=list;
         	var html='';
             for(var i=0;i<list.length;i++){	
                 html += "<option value='"+list[i].id+"'>"+list[i].name+"</option>"
             }
             $("select[name='categoryId']").append(html);
             renderForm();//表单重新渲染，要不然添加完显示不出来新的option
         }
     }); 
	
	  function sendGift(id,merchantId){
	        var index = layui.layer.open({
	            title: "发礼包",
	            type: 2,
	            content : "/card/card_detail.html?id="+id+"&mid="+merchantId,
	            success: function (layero, index) {

	            }
	        });

	        //改变窗口大小时，重置弹窗的高度，防止超出可视区域（如F12调出debug的操作）
	        $(window).resize(function () {
	            layui.layer.full(index);
	        });
	        layui.layer.full(index);
	  }
	  
	  
	  function editMember(id,merchantId){
	        var index = layui.layer.open({
	            title: "编辑会员",
	            type: 2,
	            content: "member/membersEdit.html?id="+id+"&mid="+merchantId,
	            success: function (layero, index) {

	            }
	        });

	        //改变窗口大小时，重置弹窗的高度，防止超出可视区域（如F12调出debug的操作）
	        $(window).resize(function () {
	            layui.layer.full(index);
	        });
	        layui.layer.full(index);
	  }
	</script> 
</body>
</html>